package decoder;


import enums.BaseRespCodeEnum;
import exception.AncException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import util.JsonUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @Desciption:
 * @author: Anc
 * @date: 2022/7/2
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            if (response.body() != null) {
                String targetMsg;
                String body = Util.toString(response.body().asReader());
                Map ei = JsonUtil.readValue(body, HashMap.class);
                String message = ei.get("message").toString();
                //乐观尝试HilifeException反序列化
                try {
                    return JsonUtil.readValue(message, AncException.class);
                } catch (Exception e) {
                    //服务提供者发生的异常未被拦截时进入
                    return new AncException(BaseRespCodeEnum.REMOTE_THIRD_EXCEPTION.getCode(), body);
                }

            }
        } catch (Exception e) {
            log.error("feign error decoder, methodKey:{},response:{},msg:{}", methodKey, response,
                ExceptionUtils.getStackTrace(e));
            return new AncException(BaseRespCodeEnum.SERVER_ERROR, e);
        }
        return new AncException(BaseRespCodeEnum.SERVER_ERROR);
    }
}
